package com.nofeng.wx.service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.nofeng.wx.controller.stock.view.template.WxGzhMainData;
import com.nofeng.wx.controller.stock.view.template.WxGzhVolumeData;
import com.nofeng.wx.service.stock.DailyStockData;
import com.nofeng.wx.third.EastMoneyStockApi;
import com.nofeng.wx.third.FinanceHttpApi;
import com.nofeng.wx.third.WxGzhApi;
import com.nofeng.wx.third.WxMpApi;
import com.nofeng.wx.utils.AIUtils;
import com.nofeng.wx.utils.BaseUtils;
import com.nofeng.wx.utils.TemplateUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.SimpleDateFormat;
import java.time.DayOfWeek;
import java.time.LocalDate;
import java.util.*;

@Slf4j
@Service
public class WxGzhService {
    @Autowired
    WxGzhApi wxGzhApi;

    @Autowired
    WxMpApi wxMpApi;

    @Autowired
    TemplateUtils templateUtils;

    @Autowired
    StockService stockService;

    public static final String ETF="511130,510500,159941,159915,512760,516510,518880,513090,562500,513050,159928,159867,588000,159851,512710,516150,159755,512290";

    public void today() throws Exception {
        WxGzhMainData wxGzhMainData = new WxGzhMainData();

        // 获取当前时间
        Date now = new Date();
        // 创建格式化器，指定格式为 "yyyy年MM月dd日 EEEE"
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy年MM月dd日");
        // 格式化日期
        wxGzhMainData.setNow(formatter.format(now));
        wxGzhMainData.setTitle(wxGzhMainData.getNow() + "午盘分析");

        DailyStockData sz = stockService.sz();
        DailyStockData ssz = stockService.ssz();
        DailyStockData cy = stockService.cy();
        DailyStockData kc = stockService.kc();
        wxGzhMainData.setSz(sz);
        wxGzhMainData.setSz(cy);

        SimpleDateFormat formatteryyyyMMdd = new SimpleDateFormat("yyyyMMdd");
        LocalDate today = LocalDate.now(); // 获取当前日期
        if (today.getDayOfWeek() == DayOfWeek.SATURDAY || today.getDayOfWeek() == DayOfWeek.SUNDAY) {
            return;
        }


        Map<String, Object> dataMap = wxGzhMainData.getDataMap();
        BigDecimal volumeMoney=sz.getVolumeMoney().add(ssz.getVolumeMoney());
        BigDecimal volumeMoneyYi = volumeMoney.divide(new BigDecimal("100000000"), 2, RoundingMode.HALF_UP);

        dataMap.put("volumeMoney",volumeMoneyYi+"亿");

        Map<String, Integer> count = Maps.newHashMap();
        try {
            count = EastMoneyStockApi.getCount();
        } catch (IOException e) {
            e.printStackTrace();
        }
        
        FinanceHttpApi.HttpStockData stockInfo510300 = getStock("510300");
        List<FinanceHttpApi.HttpStockData> etfDataList=Lists.newArrayList(stockInfo510300);
        List<FinanceHttpApi.HttpStockData> sellList=Lists.newArrayList();
        List<FinanceHttpApi.HttpStockData> buyList=Lists.newArrayList();
        for (String code : StringUtils.split(ETF, ",")) {
            FinanceHttpApi.HttpStockData stock = getStock(code);
            if(null!=stock){
                etfDataList.add(stock);
            }
        }
        Collections.sort(etfDataList, (o1, o2) -> o1.getRsi().compareTo(o2.getRsi()));
        for (FinanceHttpApi.HttpStockData httpStockData : etfDataList) {
            if(httpStockData.getClose().doubleValue()<httpStockData.getCutPrice().doubleValue()){
                httpStockData.setStockName("【止】"+httpStockData.getStockName());
            }
            if(httpStockData.getPrePrice().doubleValue()>=httpStockData.getCutPrice().doubleValue() && httpStockData.getClose().doubleValue()<httpStockData.getCutPrice().doubleValue()){
                httpStockData.setStockName("【卖】"+httpStockData.getStockName());
                sellList.add(httpStockData);
            }
            double buyPrice = httpStockData.getCutPrice().doubleValue()+httpStockData.getAtr60()*2;
            if(httpStockData.getPrePrice().doubleValue()<= buyPrice
                    && httpStockData.getClose().doubleValue()>=buyPrice){
                httpStockData.setStockName("【买】"+httpStockData.getStockName());
                buyList.add(httpStockData);
            }
            if(httpStockData.getClose().doubleValue()>=httpStockData.getMa14().doubleValue()){
                httpStockData.setStockName("【持】"+httpStockData.getStockName());
            }
        }
        dataMap.put("etfList", etfDataList);
        dataMap.put("sellList", sellList);
        dataMap.put("buyList", buyList);

        boolean above20ma = false;
        if (stockInfo510300.getClose().doubleValue() >= stockInfo510300.getMa20().doubleValue()) {
            above20ma = true;
        }


        dataMap.put("up_count", count.get("up"));
        dataMap.put("down_count", count.get("down"));

        double up_count_ratio = new BigDecimal(count.get("up")).doubleValue() / new BigDecimal(count.get("down") + count.get("up")).doubleValue();

        dataMap.put("up_down_ratio", BaseUtils.doubleToPtStr(up_count_ratio));


        double szChp = sz.getChgp().doubleValue();
        String szOp = szChp > 0 ? "+" : "-";

        double cyChp = cy.getChgp().doubleValue();
        String cyOp = cyChp > 0 ? "+" : "-";

        double kcChp = kc.getChgp().doubleValue();
        String kcOp = kcChp > 0 ? "+" : "-";

        dataMap.put("sz_up", szChp > 0);
        dataMap.put("sz_chp", szOp + Math.abs(szChp) + "%");
        String sc_desc_1="成交："+volumeMoneyYi+"亿";
        String sc_desc_2="预计："+new BigDecimal(volumeMoneyYi.doubleValue()*1.55).setScale(2,RoundingMode.HALF_UP).doubleValue()+"亿";
        String sc_desc_3=above20ma ? "沪深300在20均线上方" : "沪深300在20均线下方";

        dataMap.put("sz_desc_1", sc_desc_1);
        dataMap.put("sz_desc_2", sc_desc_2);
        dataMap.put("sz_desc_3", sc_desc_3);
        dataMap.put("sz_close", sz.getClose());

        dataMap.put("cy_up", cyChp > 0);
        dataMap.put("cy_chp", cyOp + Math.abs(cyChp) + "%");
        dataMap.put("cy_desc", "");
        dataMap.put("cy_close", cy.getClose());

        dataMap.put("kc_up", kcChp > 0);
        dataMap.put("kc_chp", kcOp + Math.abs(kcChp) + "%");
        dataMap.put("kc_desc", "");
        dataMap.put("kc_close", kc.getClose());

        dataMap.put("up_count", count.get("up"));
        dataMap.put("down_count", count.get("down"));
        dataMap.put("up_count_ratio", BaseUtils.doubleToPtStr(up_count_ratio));
        dataMap.put("down_count_ratio", BaseUtils.doubleToPtStr(1 - up_count_ratio));
        dataMap.put("above_20ma", above20ma ? "20均线上" : "20日均线下");


        ArrayList<WxGzhVolumeData> inVolumeDataList = Lists.newArrayList();
        ArrayList<WxGzhVolumeData> outVolumeDataList = Lists.newArrayList();
        JSONArray hotIndustry = EastMoneyStockApi.getHotIndustry(1);
        for (int i = 0; i < hotIndustry.size(); i++) {
            JSONObject industryJSON = hotIndustry.getJSONObject(i);
            String name = industryJSON.getString("f14");
            String vol = industryJSON.getString("f62");
            double volValue = BaseUtils.stringToBigDecimal(vol).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue() / 100000000;
            if (volValue > 12) {
                WxGzhVolumeData inVolume = new WxGzhVolumeData();
                inVolume.setName(name);
                inVolume.setVolumeFmt((int) Math.round(volValue));
                inVolumeDataList.add(inVolume);
            }
        }
        for (int i = hotIndustry.size() - 1; i >= hotIndustry.size() - 10; i--) {
            JSONObject industryJSON = hotIndustry.getJSONObject(i);
            String name = industryJSON.getString("f14");
            String vol = industryJSON.getString("f62");
            double volValue = BaseUtils.stringToBigDecimal(vol).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue() / 100000000;
            if (volValue < -12) {
                WxGzhVolumeData outVolume = new WxGzhVolumeData();
                outVolume.setName(name);
                outVolume.setVolumeFmt((int) Math.round(volValue));
                outVolumeDataList.add(outVolume);
            }
        }

        wxGzhMainData.setInVolumeDataList(inVolumeDataList);
        wxGzhMainData.setOutVolumeDataList(outVolumeDataList);
        dataMap.put("inVolumeDataList", inVolumeDataList);
        dataMap.put("outVolumeDataList", outVolumeDataList);
        dataMap.put("data", wxGzhMainData);

        String subTitle = AIUtils.aiForApp("1", "1985239265573654528", "SRFAsrnOYFO8JrIZKfdw0fOPFnCS4kv7");
        if(StringUtils.isNotEmpty(subTitle)){
            dataMap.put("sub_title",subTitle);
        }

        String ai = AIUtils.ai("1");
        List<String> aiList = Arrays.asList(ai.split("\n"));
//        String ai="";
        if(StringUtils.isNotEmpty(ai)) {
            dataMap.put("ai", ai);
            dataMap.put("aiList", aiList);
        }
        String financialTableHTML = templateUtils.renderHtml("financial_table", dataMap);
        System.out.println(financialTableHTML);


        String draft = wxMpApi.createDraft(wxGzhMainData.getTitle()+"-"+subTitle, subTitle,"9JH5vlxZ0cfPQz1v7B6SD3wp2rKcggGfspgAohK57jRXcEz2OU_tEaUtqO8cBHtx", financialTableHTML, "韭菜成长记");
        System.out.println(draft);
        //wxMpApi.publishDraft(draft);
    }


    public  FinanceHttpApi.HttpStockData getStock(String code){
        String stock = stockService.stock(code, false);
        JSONObject stockJSON = JSONObject.parseObject(stock);
        Double atr60 = stockJSON.getDouble("atr60");
        FinanceHttpApi.HttpStockData stockInfo = stockJSON.getObject("stock", FinanceHttpApi.HttpStockData.class);
        stockInfo.setAtr60(atr60);
        double atr60Chp = atr60 / stockInfo.getClose().doubleValue()*100;
        stockInfo.setAtr60Chp(atr60Chp);
        stockInfo.setCutPrice(stockInfo.getMa14().subtract(new BigDecimal(atr60)));
        stockInfo.setBuyPrice(stockInfo.getMa14().add(new BigDecimal(atr60)));
        stockInfo.setPrePrice(stockInfo.getPrePrice());
        return stockInfo;
    }

}
